package lxgorm

import (
	"fmt"
	"gitee.com/lxgow/lxconv"
)

// create
// 创建时间:下午4:46
// 创建人:lixu

// Create 创建
func (b *dataParams) Create(data interface{}) (rows int64, err error) {

	var i int
RESTART:
	res := SelectDb(b.dbIndex).Table(b.tableName)
	if b.debug {
		res = res.Debug()
	}
	res = res.Create(data)
	err = res.Error
	rows = res.RowsAffected
	if err == nil {
		return
	}

	if !b.autoCreate || i > 0 {
		err = fmt.Errorf("Create err=%v,%s,%s", err, lxconv.JsonEncode(b), lxconv.JsonEncode(data))
		return
	}

	if TableExist(err) {
		err = fmt.Errorf("TableExist err=%v,%s,%s", err, lxconv.JsonEncode(b), lxconv.JsonEncode(data))
		return
	}

	i++
	err = SelectDb(b.dbIndex).Table(b.tableName).AutoMigrate(data)
	if err != nil {
		err = fmt.Errorf("AutoMigrate err=%v,%s,%s", err, lxconv.JsonEncode(b), lxconv.JsonEncode(data))
		return
	}
	goto RESTART

	return
}
